package com.whzykj.common;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.codec.binary.Base64;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


public class RSAUtil {
	public static final String SIGN_ALGORITHMS = "SHA1WithRSA";

	/**
     * 用私钥对信息生成数字签名
     * @param data   //加密数据
     * @param privateKey //私钥
     * @return
     * @throws Exception
     */
    public static String sign(byte[] data,String privateKey)throws Exception{
        //解密私钥
        byte[] keyBytes = decryptBASE64(privateKey);
        //构造PKCS8EncodedKeySpec对象
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
        //指定加密算法
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        //取私钥匙对象
        PrivateKey privateKey2 = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        //用私钥对信息生成数字签名
        Signature signature = Signature.getInstance(SIGN_ALGORITHMS);
        signature.initSign(privateKey2);
        signature.update(data);
         
        return encryptBASE64(signature.sign());
    }
    
    /**
     * BASE64加密
     * @param key
     * @return
     * @throws Exception
     */
    public static String encryptBASE64(byte[] key)throws Exception{
        return (new BASE64Encoder()).encodeBuffer(key);
    }
    
    /**
     * 校验数字签名
     * @param data   加密数据
     * @param publicKey  公钥
     * @param sign   数字签名
     * @return
     * @throws Exception
     */
    public static boolean verify(byte[] data,String publicKey,String sign)throws Exception{
        //解密公钥
        byte[] keyBytes = decryptBASE64(publicKey);
        //构造X509EncodedKeySpec对象
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
        //指定加密算法
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        //取公钥匙对象
        PublicKey publicKey2 = keyFactory.generatePublic(x509EncodedKeySpec);
         
        Signature signature = Signature.getInstance(SIGN_ALGORITHMS);
        signature.initVerify(publicKey2);
        signature.update(data);
        //验证签名是否正常
        return signature.verify(decryptBASE64(sign));
    }
    
    /**
     * BASE64解密
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decryptBASE64(String key) throws Exception{
        return (new BASE64Decoder()).decodeBuffer(key);
    }
	
	/**
	 * 签名
	 * @param content
	 * @param privateKey
	 * @return
	 */
	public static String sign(String content,String keyname) {
		try {
			/*String gtwPrivateKey = loadPrivateKeyByFile(keyname);
			PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decodeBase64(gtwPrivateKey.getBytes("UTF-8")));
			KeyFactory keyf = KeyFactory.getInstance("RSA");
			PrivateKey priKey = keyf.generatePrivate(priPKCS8);
			Signature signature = Signature.getInstance(SIGN_ALGORITHMS);
			signature.initSign(priKey);
			signature.update(content.getBytes("UTF-8"));
			byte[] signed = signature.sign();
			return Base64.encodeBase64String(signed);*/
			
			return "";   //注释，待修改 2016-03-25 23:39:47
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 验证
	 * @param content
	 * @param sign
	 * @param publicKey
	 * @return
	 */
	public static boolean doCheck(String content, String sign, String srcInsCd) {
		try {
			/*String publicKey = loadPublicKeyByFile(srcInsCd);
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			byte[] encodedKey = Base64.decodeBase64(publicKey);
			PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
			java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
			signature.initVerify(pubKey);
			signature.update(content.getBytes());
			boolean bverify = signature.verify(Base64.decodeBase64(sign));
			return bverify;*/
			return true; //注释，待修改 2016-03-25 23:39:47
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 从文件加载公钥 
	 * @param path
	 * @return
	 * @throws Exception
	 */
    public static String loadPublicKeyByFile(String filename) throws Exception {  
        try {  
            BufferedReader br = new BufferedReader(new FileReader(filename));  
            String readLine = null;  
            StringBuilder sb = new StringBuilder();  
            while ((readLine = br.readLine()) != null) {  
                if (readLine.charAt(0) == '-') {
					continue;
				} else {
					sb.append(readLine);
					sb.append('\r');
				}
            }  
            br.close();  
            return sb.toString();  
        } catch (IOException e) {  
            throw new Exception("公钥数据流读取错误");  
        } catch (NullPointerException e) {  
            throw new Exception("公钥输入流为空");  
        }  
    }  
    
    /** 
     * 从文件中加载私钥 
     * @param keyFileName 
     *            私钥文件名 
     * @return 是否成功 
     * @throws Exception 
     */  
    public static String loadPrivateKeyByFile(String filename) throws Exception {  
        try {  
            BufferedReader br = new BufferedReader(new FileReader(filename));  
            String readLine = null;  
            StringBuilder sb = new StringBuilder();  
            while ((readLine = br.readLine()) != null) {  
                if (readLine.charAt(0) == '-') {
					continue;
				} else {
					sb.append(readLine);
					sb.append('\r');
				}
            }  
            br.close();  
            return sb.toString();  
        } catch (IOException e) {  
            throw new Exception("私钥数据读取错误");  
        } catch (NullPointerException e) {  
            throw new Exception("私钥输入流为空");  
        }  
    }
    
    public static String replaceBlank(String str) {
        String dest = "";
        if (str!=null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
   }
    
	
	public static void main(String[] args) throws Exception {
//		String content="08A1000709|12|192.168.1.102|2016-03-18 09:50:15|B20000001101025|http://localhost:8080/gateway/acceptNotify|http://localhost:8080/gateway/back|p0000001|user01|云支付服务费|云支付服务费";  
//        String signstr;
//		try {
//			signstr = sign(content,"D:\\lz_private_key.key");
//			System.out.println("签名串："+signstr); 
//	        boolean flag = doCheck(content, signstr, "D:\\rsa_public_key.pem"); 
//	        
//	        //String signature = RSAUtil.sign(bigstr.getBytes("UTF-8"), privateKey);
//	        
//	        System.out.println(flag);
//	        
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		String privatekey = RSAUtil.loadPrivateKeyByFile("C:\\Users\\yuandj\\Desktop\\secret_key_tools_RSA_win\\rsa_private_key_pkcs8.pem");
		 System.out.println(replaceBlank(privatekey));
		
		String a="MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBALQJcaf0Kisq4Em5ibXHzyhD84jMp3OLIhF8YRpYPKL5ORgdf2AFO6axFkuH4F90SYUU8IhCEz30l/++uhj16sUGHVa1vDHN6zTrhJBPdf88ks4j1DkIc3KRiMLNkAciVfGWuNcXK8VEq+ItrKNxlB4fvVWN2pNAGNSvSTbhUj3jAgMBAAECgYEAlg4VA9Z22xnWbLxOsgsCd14Dei6RFrWNRKO1Tz7h8zfjxVy4kHBsImgQ3A05DnYe3OPyAq+H2CioE4mFFE7LR9vOtOS7urGssr/9PeF4bzzsGIE0WUS+lhhhTwGUgont27RQIuzvngzeRoAcMwcqT8MrKa8ADK706IwqkFlS++kCQQDevZ8ybHj0msZrslkxVLKxuGP2J+oKWaYkz9oas0yHKko0k63ZH56gbUA9zELo4RpYs4yVIqP+VjSc3/j5NnfHAkEAzutyVx4tYYyWdskI48UqRGDOxsEl4XOrvqS2Wa1Zz24Cap1eTyfsmX3t05M4Q6+8A1BX86Tif+5MSbfNVCThBQJBALNrvWwJspkef8zK2kwBdPvxkxv65Oy3cDzg7Uhqu695YlLdzsFCVi3WM1RUUGV0xhtDbm/HeqBqYnEnfU+KD4sCQQDKqebSlvcBzU3tyBdR52HvmRXNq43rlHyJfBAyI0yMkwYA4GNnigX9jE6s5Eu+V9gBMucB9uP1QzQrG8AbAwf1AkBA/QLQEanCr1vWWBEQYU7Ei2EubLeMu5eDSN/ey9lboBZ/iYwT9KTUxqUsbVoyVraH+q+hhbufXu0njb1U3mtX";
		
		if(a.equals(replaceBlank(privatekey))){
			System.out.print(1);
		}
	}
}
